package Filter;

import dao.ShopDao;
import dao.UserDao;
import pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        request.setCharacterEncoding("UTF-8");

        //未进入登录状态
        HttpSession session = request.getSession();
        boolean flag1 = session.getAttribute("user") == null;

        //Cookie有账号|密码
        String account = null;
        String password = null;
        Cookie[] cookies = request.getCookies();  //获取Cookie
        if (cookies != null) {  //如果获取到了
            boolean flag2 = false;
            for (Cookie c : cookies) {
                if (c.getName().equals("account")) {
                    account = c.getValue();
                } else if (c.getName().equals("password")) {
                    password = c.getValue();
                }

                if (account != null && password != null) {
                    flag2 = true;
                    break;
                }
            }

            if (flag1 && flag2) {
                UserDao dao = new UserDao();
                User user = dao.findOne(account);
                if (user != null && password.equals(user.getPassword())) {
                    session.setAttribute("userName", user.getUsername());
                    session.setAttribute("userJudge","退出登录");
                    session.setAttribute("user", user);
                }
            } else {
                session.setAttribute("userName", "登录");
                session.setAttribute("userJudge","注册");
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            session.setAttribute("userName", "登录");
            session.setAttribute("userJudge","注册");
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
